package cn.com.mma.mobile.tracking.api;

import java.net.URI;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;

import android.content.Context;
import android.content.SharedPreferences;
import cn.com.mma.mobile.tracking.util.DeviceInfoUtil;
import cn.com.mma.mobile.tracking.util.Logger;
import cn.com.mma.mobile.tracking.util.SharedPreferencedUtil;

/**
 * 发送消息的线程
 * 
 * @author lincoln
 * 
 */
public class SendMessageThread extends Thread {

	private String spName;
	private Context context;
	private boolean isNormalList;
	private boolean isInterruptThread = false;// 是否中断线程
	public int totalSize = 0;

	@Override
	public void interrupt() {
		isInterruptThread = true;
		super.interrupt();
	}

	SendMessageThread(String spFileName, Context context, boolean isNormalList) {
		this.spName = spFileName;
		this.context = context;
		this.isNormalList = isNormalList;
	}

	@Override
	public void run() {
		sendData();
	}

	private void sendData() {
		for (String key : SharedPreferencedUtil.getSharedPreferences(context, spName).getAll().keySet()) {
			if (isInterruptThread) {
				return;
			}
			if (!DeviceInfoUtil.isNetworkAvailable(context))
				return;
			Long valueExpire = null;
			try {
				valueExpire = SharedPreferencedUtil.getLong(context, spName, key);
				String data = key;
				if (data == null || "".equals(data))
					continue;
				if (valueExpire > System.currentTimeMillis()) {
					HttpResponse httpResponse = sendMessage(data);
					Logger.d("isNormal:" + isNormalList + " mma_request_sendUrl:" + data);
					if (httpResponse == null) {
						handleFailedResult(key, valueExpire);
						continue;
					}
					int statueCode = httpResponse.getStatusLine().getStatusCode();
					Logger.d("mma_result_code:" + statueCode);
					if (statueCode == 200 || statueCode == 301 || statueCode == 302) {
						handleSuccessResult(spName, key);
					} else {
						handleFailedResult(key, valueExpire);
					}
				} else {
					/**
					 * 超出有效期则删除
					 */
					SharedPreferencedUtil.removeFromSharedPreferences(context, spName, key);
				}
			} catch (Exception e) {
				e.printStackTrace();
				continue;
			}
		}
	}

	/**
	 * 发送消息，返回结果
	 * 
	 * @param data
	 * @return
	 */
	private HttpResponse sendMessage(String data) {
		DefaultHttpClient httpClient = null;
		HttpGet method = null;
		HttpResponse httpResponse = null;
		try {
			httpClient = new DefaultHttpClient();
			httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, Global.OFFLINECACHE_TIMEOUT * 1000);
			httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, Global.OFFLINECACHE_TIMEOUT * 1000);
			method = new HttpGet(new URI(data));
			httpResponse = httpClient.execute(method);
		} catch (Exception e) {
			e.printStackTrace();
			Logger.d("mma_result_error发送失败");
		} finally {
			if (httpClient != null && httpClient.getConnectionManager() != null) {
				httpClient.getConnectionManager().shutdown();
			}
		}
		return httpResponse;
	}

	/**
	 * 消息发送失败处理逻辑
	 */
	private void handleFailedResult(String key, long valueExpire) {
		if (isNormalList) {
			// 从正常列表删除，存储到失败列表
			SharedPreferencedUtil.removeFromSharedPreferences(context, SharedPreferencedUtil.SP_NAME_NORMAL, key);
			SharedPreferencedUtil.putLong(context, SharedPreferencedUtil.SP_NAME_FAILED, key, valueExpire);
			SharedPreferencedUtil.putLong(context, SharedPreferencedUtil.SP_NAME_OTHER, key, 1);
		} else {
			// 错误列表发送失败超过3次，则删除
			long failedTime = SharedPreferencedUtil.getLong(context, SharedPreferencedUtil.SP_NAME_OTHER, key);
			failedTime += 1;
			if (failedTime > 3) {
				SharedPreferencedUtil.removeFromSharedPreferences(context, SharedPreferencedUtil.SP_NAME_FAILED, key);
				boolean result = SharedPreferencedUtil.removeFromSharedPreferences(context, SharedPreferencedUtil.SP_NAME_OTHER, key);
				Logger.d("mma_failed发送失败超过三次，删除other中记录" + result);
			} else {
				SharedPreferencedUtil.putLong(context, SharedPreferencedUtil.SP_NAME_OTHER, key, failedTime);
			}
		}
	}

	/**
	 * 消息发送成功处理逻辑
	 */
	private void handleSuccessResult(String sharedPreferencedName, String key) {
		SharedPreferencedUtil.removeFromSharedPreferences(context, sharedPreferencedName, key);
		if (!isNormalList) {
			// 删除错误日志中的失败次数
			boolean result = SharedPreferencedUtil.removeFromSharedPreferences(context, SharedPreferencedUtil.SP_NAME_OTHER, key);
			Logger.d("mma_failed数据发送成功，删除other中记录" + result);

		}

	}
}
